/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package ru.dusty.fs.copy;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import ru.dusty.fs.filesystem.data.Block;
import ru.dusty.fs.filesystem.data.BlocksMap;
import ru.dusty.fs.filesystem.exceptions.FileAlreadyExistsException;
import ru.dusty.fs.filesystem.utils.Utils;

/**
 *
 * @author Dusty
 */
public class CopyFs {
    
    private static final String NAME = "copy";
    
    private BlocksMap map;
    
    public int copy(String[] args) {
        if (args.length < 3) {
            System.out.println(NAME + ": missing operand after \"" + NAME + "\"");
            System.out.println(NAME + ": use \"" + NAME + " root src dst\"");
            return 1;
        }
        
        String root = args[0];
        try {
            if (!Utils.isFsFormatted(root)) {
                System.out.println(NAME + ": File system error.");
                System.out.println(NAME + ": Use the command \"format root\"");
                return 5;
            }
            
            List<String> srcPath = Utils.parsePath(args[1]);
            Block srcBlock = Utils.getFirstBlock(root, srcPath);
            
            if (srcBlock == null) {
                System.out.println(NAME + ": " + args[1] + ": No such file or directory.");
                return 6;
            }
            
            map = new BlocksMap(root, Utils.getBlocksCount(root));
            map.initMap();
            
            List<String> dstPath = Utils.parsePath(args[2]);
            if (!Utils.isCorrectPathToCopy(srcPath, dstPath)) {
                System.out.println(NAME + ": Can not copy a directory " + args[1]
                + " in itself, " + args[2]);
                return 9;
            }
            
            Utils.copy(root, map, srcPath, dstPath);
        } catch (FileAlreadyExistsException ex) {
            System.out.println(NAME + ": Unable to create the specified directory.");
            System.out.println(NAME + ": " + ex.getFile() + ": such file already existed.");
            return 7;
        } catch (FileNotFoundException ex) {
            System.out.println(NAME + ": Could not find the file block.");
            System.out.println(NAME + ": " + ex.getMessage());
            return 2;
        } catch (OutOfMemoryError ex) {
            System.out.println(NAME + ": Memory error.");
            System.out.println(NAME + ": " + ex.getMessage());
            return 8;
        } catch (IOException ex) {
            System.out.println(NAME + ": Error occurred while reading the file block.");
            System.out.println(NAME + ": " + ex.getMessage());
            return 3;
        }
        
        return 0;
    }
    
}
